package org.ruiyichen.guizhou.agr.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

/**
 * Created by Administrator
 */
public class NetWorkUtils {

    private NetWorkUtils(){
        throw new UnsupportedOperationException("cannot be instantiated");
    }

    public interface Type{
        int NO_NETWORK_CONNECTION = -1;
        int MOBILE_NETWORK = 1;
        int WIFI_NETWORK = 2;
    }

    /**
     * 检查网络是否可用
     * @param context
     * @return
     */
    public static int checkNetConnect(Context context) {
        int connect = Type.NO_NETWORK_CONNECTION;
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = manager.getActiveNetworkInfo();
        if (info == null) {  //无网情况下
            //跳转到网络设置页面
//            context.startActivity(new Intent(android.provider.Settings.ACTION_SETTINGS));
        } else {   //有网情况下
            if (info.isAvailable()) { //网络可用时
                /**是手机自带的联网方式*/
                if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
                    if (info.getState() == NetworkInfo.State.CONNECTED) {
                        connect = Type.MOBILE_NETWORK;
                    }
                } else { /**WIFI联网方式*/
                    connect = Type.WIFI_NETWORK;
                }
            }
        }
        return connect;
    }

    /**
     * 用来获取手机拨号上网（包括CTWAP和CTNET）时由PDSN分配给手机终端的源IP地址。
     * @return
     * @author SHANHY
     */
    public static String getPsdnIp() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                        //if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet6Address) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (Exception e) {
        }
        return "127.0.0.1";
    }



    static long postTime;
    static long mParams;
    /**
     * 判断是否短时间多次操作
     *
     * @return true 是 没有超出规定操作间隔时间不可以操作 返回 false否 可以操作
     * @see [类、类#方法、类#成员]
     */
    public static boolean isMostPost() {
        long time = System.currentTimeMillis();

        long timeD = time - postTime;
        // 如果距离上次操作时间小于0.5秒就不做操作
        if (timeD > 0 && timeD < 500) {

            return true;
        }
        postTime = time;
        return false;
    }

}
